package com.summer.filesync.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.summer.filesync.util.Logger;
import java.util.HashMap;
import java.util.Map;

/** 安全HTTP请求处理器 为HTTP API添加认证和授权功能 */
public class SecurityHandler {
  private static final Logger logger = Logger.getLogger(SecurityHandler.class);
  private final AuthenticationService authService;
  private final ObjectMapper objectMapper;

  public SecurityHandler() {
    this.authService = AuthenticationService.getInstance();
    this.objectMapper = new ObjectMapper();
  }

  /**
   * 处理登录请求
   *
   * @param requestBody 请求体
   * @return 响应JSON
   */
  public String handleLogin(String requestBody) {
    try {
      @SuppressWarnings("unchecked")
      Map<String, String> loginData = objectMapper.readValue(requestBody, Map.class);

      String username = loginData.get("username");
      String password = loginData.get("password");

      if (username == null || password == null) {
        return createErrorResponse("用户名和密码不能为空");
      }

      AuthenticationResult result = authService.authenticate(username, password);

      if (result.isSuccess()) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("token", result.getToken());
        response.put("username", result.getUsername());
        response.put("role", result.getRole().getCode());
        response.put("message", "登录成功");

        return objectMapper.writeValueAsString(response);
      } else {
        return createErrorResponse(result.getErrorMessage());
      }

    } catch (Exception e) {
      logger.error("Login request processing failed", e);
      return createErrorResponse("登录请求处理失败");
    }
  }

  /**
   * 处理注销请求
   *
   * @param token JWT令牌
   * @return 响应JSON
   */
  public String handleLogout(String token) {
    try {
      authService.logout(token);

      Map<String, Object> response = new HashMap<>();
      response.put("success", true);
      response.put("message", "注销成功");

      return objectMapper.writeValueAsString(response);

    } catch (Exception e) {
      logger.error("Logout request processing failed", e);
      return createErrorResponse("注销请求处理失败");
    }
  }

  /**
   * 验证请求权限
   *
   * @param token 认证令牌
   * @param requiredRole 所需角色
   * @return 认证结果
   */
  public AuthenticationResult validateRequest(String token, UserRole requiredRole) {
    if (token == null || token.trim().isEmpty()) {
      return AuthenticationResult.failure("缺少认证令牌");
    }

    AuthenticationResult result;

    // 如果令牌以"Bearer "开头，则为JWT令牌
    if (token.startsWith("Bearer ")) {
      String jwtToken = token.substring(7);
      result = authService.authenticateToken(jwtToken);
    }
    // 否则尝试作为API密钥处理
    else {
      result = authService.authenticateApiKey(token);
    }

    if (!result.isSuccess()) {
      return result;
    }

    // 检查权限
    if (!result.hasPermission(requiredRole)) {
      return AuthenticationResult.failure("权限不足，需要" + requiredRole.getDescription() + "权限");
    }

    return result;
  }

  /**
   * 验证请求权限（按级别）
   *
   * @param token 认证令牌
   * @param requiredLevel 所需权限级别
   * @return 认证结果
   */
  public AuthenticationResult validateRequest(String token, int requiredLevel) {
    if (token == null || token.trim().isEmpty()) {
      return AuthenticationResult.failure("缺少认证令牌");
    }

    AuthenticationResult result;

    // 如果令牌以"Bearer "开头，则为JWT令牌
    if (token.startsWith("Bearer ")) {
      String jwtToken = token.substring(7);
      result = authService.authenticateToken(jwtToken);
    }
    // 否则尝试作为API密钥处理
    else {
      result = authService.authenticateApiKey(token);
    }

    if (!result.isSuccess()) {
      return result;
    }

    // 检查权限级别
    if (!result.hasPermission(requiredLevel)) {
      return AuthenticationResult.failure("权限不足，需要级别 " + requiredLevel + " 权限");
    }

    return result;
  }

  /**
   * 获取系统安全状态
   *
   * @return 安全状态JSON
   */
  public String getSecurityStatus() {
    try {
      Map<String, Object> status = new HashMap<>();
      status.put("activeSessionCount", authService.getActiveSessionCount());
      status.put("userCount", authService.getUserList().size());
      status.put("authenticationEnabled", true);
      status.put("jwtEnabled", true);
      status.put("apiKeyEnabled", true);

      Map<String, Object> response = new HashMap<>();
      response.put("success", true);
      response.put("data", status);

      return objectMapper.writeValueAsString(response);

    } catch (Exception e) {
      logger.error("Failed to get security status", e);
      return createErrorResponse("获取安全状态失败");
    }
  }

  /**
   * 创建用户（需要管理员权限）
   *
   * @param requestBody 请求体
   * @param adminToken 管理员令牌
   * @return 响应JSON
   */
  public String createUser(String requestBody, String adminToken) {
    try {
      // 验证管理员权限
      AuthenticationResult authResult = validateRequest(adminToken, UserRole.ADMIN);
      if (!authResult.isSuccess()) {
        return createErrorResponse(authResult.getErrorMessage());
      }

      @SuppressWarnings("unchecked")
      Map<String, String> userData = objectMapper.readValue(requestBody, Map.class);

      String username = userData.get("username");
      String password = userData.get("password");
      String roleStr = userData.get("role");
      String description = userData.get("description");

      if (username == null || password == null || roleStr == null) {
        return createErrorResponse("用户名、密码和角色不能为空");
      }

      UserRole role = UserRole.fromCode(roleStr);
      if (role == UserRole.ANONYMOUS) {
        return createErrorResponse("无效的用户角色");
      }

      boolean success = authService.createUser(username, password, role, description);

      if (success) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户创建成功");
        response.put("username", username);
        response.put("role", role.getCode());

        return objectMapper.writeValueAsString(response);
      } else {
        return createErrorResponse("用户名已存在");
      }

    } catch (Exception e) {
      logger.error("User creation failed", e);
      return createErrorResponse("用户创建失败");
    }
  }

  /**
   * 创建API密钥（需要管理员权限）
   *
   * @param requestBody 请求体
   * @param adminToken 管理员令牌
   * @return 响应JSON
   */
  public String createApiKey(String requestBody, String adminToken) {
    try {
      // 验证管理员权限
      AuthenticationResult authResult = validateRequest(adminToken, UserRole.ADMIN);
      if (!authResult.isSuccess()) {
        return createErrorResponse(authResult.getErrorMessage());
      }

      @SuppressWarnings("unchecked")
      Map<String, String> keyData = objectMapper.readValue(requestBody, Map.class);

      String owner = keyData.get("owner");
      String roleStr = keyData.get("role");
      String description = keyData.get("description");

      if (owner == null || roleStr == null) {
        return createErrorResponse("所有者和角色不能为空");
      }

      UserRole role = UserRole.fromCode(roleStr);
      if (role == UserRole.ANONYMOUS) {
        return createErrorResponse("无效的用户角色");
      }

      String apiKey = authService.createApiKey(owner, role, description);

      Map<String, Object> response = new HashMap<>();
      response.put("success", true);
      response.put("message", "API密钥创建成功");
      response.put("apiKey", apiKey);
      response.put("owner", owner);
      response.put("role", role.getCode());

      return objectMapper.writeValueAsString(response);

    } catch (Exception e) {
      logger.error("API key creation failed", e);
      return createErrorResponse("API密钥创建失败");
    }
  }

  /**
   * 创建错误响应
   *
   * @param errorMessage 错误信息
   * @return 错误响应JSON
   */
  private String createErrorResponse(String errorMessage) {
    try {
      Map<String, Object> response = new HashMap<>();
      response.put("success", false);
      response.put("error", errorMessage);

      return objectMapper.writeValueAsString(response);
    } catch (Exception e) {
      logger.error("Failed to create error response", e);
      return "{\"success\":false,\"error\":\"内部服务器错误\"}";
    }
  }

  /**
   * 创建成功响应
   *
   * @param data 数据
   * @return 成功响应JSON
   */
  public String createSuccessResponse(Object data) {
    try {
      Map<String, Object> response = new HashMap<>();
      response.put("success", true);
      response.put("data", data);

      return objectMapper.writeValueAsString(response);
    } catch (Exception e) {
      logger.error("Failed to create success response", e);
      return createErrorResponse("响应创建失败");
    }
  }

  /**
   * 解析Authorization header
   *
   * @param authHeader Authorization header值
   * @return 认证令牌
   */
  public static String parseAuthToken(String authHeader) {
    if (authHeader == null) {
      return null;
    }

    // 支持Bearer令牌格式
    if (authHeader.startsWith("Bearer ")) {
      return authHeader.substring(7);
    }

    // 支持Basic格式（用于API密钥）
    if (authHeader.startsWith("Basic ")) {
      return authHeader.substring(6);
    }

    // 直接返回原始值（API密钥）
    return authHeader;
  }
}
